package com.pactera.jep.service.sys.web.controller;

import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.entity.Treeable;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.service.sys.dto.DictCateDto;
import com.pactera.jep.sys.model.DictCate;
import com.pactera.jep.sys.service.DictCateService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.TreeNode;
import com.pactera.jep.web.util.TreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Yangyao
 * @time 2018年06月15日 10:57
 * @company 文思海辉技术有限公司
 */
@Api(value = "字典类别管理")
@RestController
@RequestMapping("/dictCate")
public class DictCateRestController extends BaseRestController<DictCate> {
    Logger logger = LoggerFactory.getLogger(DictCateRestController.class);

    @Autowired
    DictCateService dictCateService;

    /**
     * 获取当前用户能访问的菜单
     * @return
     */
    @ApiOperation(value = "加载数据")
    @GetMapping("/load")
    public List<DictCateDto> load()
    {
        List<DictCateDto> dictCateDtos = new ArrayList<>();

        List<DictCate> dictCates = dictCateService.selectAll();
        for(DictCate dictCate : dictCates)
        {
            DictCateDto dictCateDto = new DictCateDto();

            dictCateDto.setId(dictCate.getDictCateCode());
            dictCateDto.setTitle(dictCate.getDictCateName());
            if(StringUtils.isNotBlank(dictCate.getParentId()))
            {
                String parentName = dictCateService.get(dictCate.getParentId()).getDictCateName();
                dictCateDto.setParentName(parentName);
            }
            dictCateDto.setParentId(dictCate.getParentId());
            dictCateDto.setDictCateCode(dictCate.getDictCateCode());
            dictCateDto.setDictCateName(dictCate.getDictCateName());
            dictCateDto.setDictCateDesc(dictCate.getDictCateDesc());

            dictCateDtos.add(dictCateDto);
        }
        return generateAppConfigDto(null, dictCateDtos);
    }

    private List<DictCateDto> generateAppConfigDto(DictCateDto parent, List<DictCateDto> dictCateDtos){

        List<DictCateDto> data = new ArrayList<>();

        for(DictCateDto dictCateDto : dictCateDtos){
            if(parent != null && parent.getId().equals(dictCateDto.getParentId()))
            {
                dictCateDto.setChildren(generateAppConfigDto(dictCateDto, dictCateDtos));
                data.add(dictCateDto);
            }
            else if(parent == null && StringUtils.isBlank(dictCateDto.getParentId())){
                dictCateDto.setChildren(generateAppConfigDto(dictCateDto, dictCateDtos));
                data.add(dictCateDto);
            }
        }
        return data;
    }

    /**
     * 移除节点
     * @param dictCateCode
     * @return
     */
    @ApiOperation(value = "根据编码删除一条数据")
    @PostMapping(value = "/removeNode/{dictCateCode}")
    public Map<String, Object> removeNode(@PathVariable String dictCateCode) {
        Map<String, Object> tips = new HashMap<String, Object>();

        /*查询当前节点是否有子节点*/
        long count = dictCateService.count(new Filter.Builder().eq("parentId", dictCateCode).build());

        /*总数大于0，提示先删除子节点，反之进行删除*/
        if(count > 0)
        {
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.DELETE_SUBNODE_FIRST);
        }
        else
        {
            try{
                dictCateService.deleteByPrimaryKey(dictCateCode);
                tips.put(WebCode.SUCCESS, true);
                tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
            }
            catch (ServiceException e) {
                logger.info(e.getMessage());
                tips.put(WebCode.SUCCESS, false);
                tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
            }
        }
        return tips;
    }

    /**
     * 重命名节点
     * @param dictCateCode 节点key
     * @param newName 节点新的名称
     * @return
     */
    @ApiOperation(value = "根据编码节点name")
    @PostMapping(value = "/renameNode/{dictCateCode}")
    public Map<String, Object> renameNode(@PathVariable String dictCateCode, String newName) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            DictCate dictCate= new DictCate();
            dictCate.setDictCateCode(dictCateCode);
            dictCate.setDictCateName(newName);
            dictCateService.update(dictCate, new String[]{"DictCateName"});

            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_RENAME);
        }
        catch(ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAULURE_RENAME);
        }
        return tips;
    }

    /**
     * 新增或保存节点
     * @param dictCate
     * @return
     */
    @ApiOperation(value = "新增或保存一个节点")
    @PostMapping(value = "/updateNode")
    public Map<String, Object> updateNode(@RequestBody DictCate dictCate) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try
        {
            Boolean isExist = dictCateService.exists(dictCate.getDictCateCode());
            /*判断当前对象是否存在, 不存在就添加*/
            if(isExist)
            {
                dictCateService.update(dictCate);
            }
            else
            {
                dictCateService.insert(dictCate);
            }
            tips.put(Treeable.TREE_ID, dictCate.getDictCateCode());
            tips.put(WebCode.SUCCESS, true);
            tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
        }
        catch(ServiceException e)
        {
            logger.info(e.getMessage());
            tips.put(WebCode.SUCCESS, false);
            tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
        }
        return tips;
    }

    /**
     * 初始化加载数据
     * @param parentId
     * @param request
     * @return
     */
    @ApiOperation(value = "加载树节点")
    @GetMapping(value = "/treeNode")
    public List<TreeNode> treeNode(String parentId, HttpServletRequest request) {
        List<Filter> filters = null;

        if(parentId == null)
        {
            filters = new Filter.Builder().nl("parentId").build();
        }
        else
        {
            filters = new Filter.Builder().eq("parentId", parentId).build();
        }

        List<DictCate> list = dictCateService.select(filters);

        String[] columns = new String[]{
                "dictCateCode",
                "dictCateName",
                "dictCateDesc",
                "parentId",
        };

        List<TreeNode> nodes = TreeUtils.parse(list, columns);
        return nodes;
    }
}
